package DAO.DAOImple;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import util.DBTool;
import util.Encoding;
import util.SecurityTools;

import DAO.UserDAO;
import model.Group;
import model.HeadImg;
import model.Page;
import model.PassModify;
import model.User;
import model.UserLoginLog;
/**
 * @author BangBang bangbang668@gmail.com)
 *
 */
public class UserDAOImple implements UserDAO {

	public int userLogin(User user) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0; 
		DBTool dbt = DBTool.getDBTool();
		String sql = "select * from T_User where name = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setString(1, user.getName());
			rs = pstmt.executeQuery();

			if (rs.next()) {
				int id = rs.getInt("id");
				String pass = rs.getString("password");
				int logintime = rs.getInt("logintime");
				int jifen = rs.getInt("jifen") + 2;
				user.setId(id);
				System.out.println(SecurityTools.encrypt("AUST",pass));
				if (pass.equals(SecurityTools.encrypt("AUST",user.getPassword()))) {
					
					result = 2;  //登陆成功
					
					sql="update T_User set loginTime = ?,jifen = ? where id = ?";  //更新用户数据
					pstmt = dbt.getPstmt(sql);
					pstmt.setInt(1, ++logintime);
					pstmt.setInt(2, jifen);
					pstmt.setInt(3, user.getId());
					pstmt.executeUpdate();
					user.setLogintime(logintime);
					
					
				}else {
					result = 1;  //密码不正确
				}
				
				if(result == 2) {   //若登陆成功 则记录登陆信息
					HttpServletRequest request = ServletActionContext. getRequest();
					
					UserLoginLog loginlog = new UserLoginLog(new Date(),user.getId(),request.getRemoteAddr());
					sql = "insert into T_UserLoginLog(loginTime,loginUser,loginIP) values(?,?,?)";
					
					pstmt = dbt.getPstmt(sql);
					pstmt.setString(1, (new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss").format(loginlog.getLoginTime())));
					pstmt.setInt(2, loginlog.getLoginUser());
					pstmt.setString(3, loginlog.getLoginIP());
					pstmt.executeUpdate();
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public int addUser(User user) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0;   //默认为0，
		DBTool dbt = DBTool.getDBTool();
		String sql = "select * from T_User where name = ?";
		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setString(1, user.getName());
			rs = pstmt.executeQuery();

			if (rs.next()) {
				result = 1;   //用户已存在
			}else {
				sql = "insert into T_User(name,password) values(?,?)";
				pstmt = dbt.getPstmt(sql);
				pstmt.setString(1, user.getName());
				pstmt.setString(2,SecurityTools.encrypt("AUST",user.getPassword()));
				int res = pstmt.executeUpdate();
				if(res != 0) {
					result = 2; //增加成功
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public List<User> getUserList(Page page) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		
		List<User> users = new ArrayList<User>();
		User user = null;
		String sql = "SELECT u.*,g.groupName as groupName,h.ImgSrc as ImgSrc FROM " 
			+ "T_User as u,T_Group as g,T_HeadImg as h" 
			+ " where u.groupID = g.id and u.headImg = h.id and u.state = 0 order by u.id limit ?,?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1, page.getStartRow());
			pstmt.setInt(2, page.getPageSize());
			rs = pstmt.executeQuery();

			while(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setJoinTime(rs.getDate("joinTime"));
				user.setSex(rs.getString("sex"));
				//user.setGroup(new Group(rs.getInt("groupID"),rs.getString("groupName")));
			user.setGroup(new Group(rs.getInt("groupID"),Encoding.isoToGBK(rs.getString("groupName"))));
				user.setPost(rs.getInt("post"));
				user.setPhone(rs.getString("phone"));
				user.setMajor(Encoding.isoToGBK(rs.getString("major")));
			//user.setMajor(rs.getString("major"));
				user.setHeadImg(new HeadImg());
				user.getHeadImg().setImgSrc(rs.getString("ImgSrc"));
				user.setQq(rs.getString("qq"));
				user.setLogintime(rs.getInt("loginTime"));
				user.setJiFen(rs.getInt("jifen"));
				
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return users;
	}

	public int PassModify(PassModify PModify, User user) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0; 
		DBTool dbt = DBTool.getDBTool();
		
		String sql = "select password from T_User where id = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1,user.getId());
			rs = pstmt.executeQuery();
			if(rs.next()) {
				if(PModify.getOldPass().equals(rs.getString("password"))) {
					sql = "update T_User set password = ? where id = ?";
					pstmt = dbt.getPstmt(sql);
					pstmt.setString(1,PModify.getNewPass());
					pstmt.setInt(2, user.getId());
					int uRs = pstmt.executeUpdate();
					if(uRs != 0) {
						result = 2;
					}else {
						result = 0;
					}
				}else {
					result = 1;
				}
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public User getUser(int id) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		
		User user = null;
		String sql = "select u.*,g.id as groupID,g.groupName as groupName,h.ImgSrc as ImgSrc from " 
			+ "T_User as u,T_Group as g,T_HeadImg as h" 
			+ " where u.groupID = g.id and u.headImg = h.id and u.id = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();

			if(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setJoinTime(rs.getDate("joinTime"));
				user.setSex(rs.getString("sex"));
				user.setGroup(new Group(rs.getInt("groupID"),Encoding.isoToGBK(rs.getString("groupName"))));
			//user.setGroup(new Group(rs.getInt("groupID"),rs.getString("groupName")));
				user.setPost(rs.getInt("post"));
				user.setPhone(rs.getString("phone"));
				//user.setMajor(Encoding.isoToGBK(rs.getString("major")));
				System.out.println(rs.getString("major"));
				user.setMajor(rs.getString("major"));
//			user.setMajor(rs.getString("major"));
				user.setHeadImg(new HeadImg());
				user.getHeadImg().setImgSrc(rs.getString("ImgSrc"));
				user.setQq(rs.getString("qq"));
				user.setLogintime(rs.getInt("loginTime"));
				user.setJiFen(rs.getInt("jiFen"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return user;
	}

	public User getUser(String name) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		
		User user = null;
		String sql = "select u.*,g.id as groupID,g.groupName as groupName,h.ImgSrc as ImgSrc from " 
			+ "T_User as u,T_Group as g,T_HeadImg as h" 
			+ " where u.groupID = g.id and u.headImg = h.id and u.name = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setString(1, name);
			rs = pstmt.executeQuery();

			if(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setJoinTime(rs.getDate("joinTime"));
				user.setSex(rs.getString("sex"));
//				user.setGroup(new Group(rs.getInt("groupID"),rs.getString("groupName")));
				user.setGroup(new Group(rs.getInt("groupID"),Encoding.isoToGBK(rs.getString("groupName"))));
				user.setPost(rs.getInt("post"));
				user.setPhone(rs.getString("phone"));
				user.setMajor(Encoding.isoToGBK(rs.getString("major")));
//			user.setMajor(rs.getString("major"));
				user.setHeadImg(new HeadImg());
				user.getHeadImg().setImgSrc(rs.getString("ImgSrc"));
				user.setQq(rs.getString("qq"));
				user.setLogintime(rs.getInt("loginTime"));
				user.setJiFen(rs.getInt("jiFen"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return user;
	}
	
	public int infoModify(User user) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0;  //默认为0 失败
		DBTool dbt = DBTool.getDBTool();
		
		String sql = "select * from T_User where id != ? and name = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1,user.getId());
			pstmt.setString(2,user.getName());
			rs = pstmt.executeQuery();
			if(rs.next()) {
				result = 1;   //用户名已存在
			}else {
				sql = "update T_User set name = ?,joinTime = ?,sex = ?,groupID = ?,post = ?,phone = ?,major = ?,qq = ? where id = ? ";
				pstmt = dbt.getPstmt(sql);
				pstmt.setString(1, user.getName());
				pstmt.setString(2, (new SimpleDateFormat( "yyyy-MM-dd").format(user.getJoinTime())));
				pstmt.setString(3,user.getSex());
				pstmt.setInt(4, user.getGroup().getId());
				pstmt.setInt(5, user.getPost());
				pstmt.setString(6, user.getPhone());
				pstmt.setString(7, user.getMajor());
			System.out.println(user.getMajor() + "-----------");
				pstmt.setString(8,user.getQq());
				pstmt.setInt(9, user.getId());
				int urs = pstmt.executeUpdate();
			System.out.println(user.getPost());
				if(urs != 0) {
					result = 2; //更新成功
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public int changeHeadImg(User user, HeadImg headImg) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0;  //默认为0 失败 1 成功
		DBTool dbt = DBTool.getDBTool();
		
		String sql = "insert into T_HeadImg(headName,imgSrc,userId) values(?,?,?)";  //向t_headImg表中插入数据
		String headName = headImg.getHeadName().substring(0,headImg.getHeadName().lastIndexOf("."));
		String imgSrc = headImg.getImgSrc() + "/" + headImg.getHeadName();

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setString(1,headName);
			pstmt.setString(2,imgSrc);
			pstmt.setInt(3, user.getId());
			int urs = pstmt.executeUpdate();
			if(urs != 0) {
				sql ="select * from T_HeadImg where headName = ?";
				pstmt = dbt.getPstmt(sql);
				pstmt.setString(1, headName);
				rs = pstmt.executeQuery();
				if(rs.next()) {
					headImg.setId(rs.getInt("id"));
					sql = "update T_User set headImg = ? where id = ?";
					pstmt = dbt.getPstmt(sql);
					pstmt.setInt(1, headImg.getId());
					pstmt.setInt(2, user.getId());
					pstmt.executeUpdate();
					
					result = 1;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public int deleteUser(User user) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		int result = 0;  //默认为0 失败 1 成功
		DBTool dbt = DBTool.getDBTool();
		
		String sql = "update T_User set state = ? where id =?";
		
		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1,1);
			pstmt.setInt(2, user.getId());
			int urs = pstmt.executeUpdate();
			if(urs != 0) {
				result = 1;  //删除成功
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}

	public List<HeadImg> getHeadImgList(int id) {
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		
		List<HeadImg> headImgs = new ArrayList<HeadImg>();
		HeadImg headImg = null;
		String sql = "select * from T_HeadImg where userId = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();

			while(rs.next()) {
				headImg = new HeadImg();
				headImg.setId(rs.getInt("id"));
				headImg.setHeadName(rs.getString("headName"));
				headImg.setImgSrc(rs.getString("ImgSrc"));
				
				headImgs.add(headImg);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rs);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return headImgs;
	}

	public int modifyImg(int userId, int headImgId) {
		PreparedStatement pstmt = null;
		int result = 0;  //默认为0 失败 1 成功
		DBTool dbt = DBTool.getDBTool();
		
		String sql = "update T_User set headImg = ? where id = ?";

		try {
			pstmt = dbt.getPstmt(sql);
			pstmt.setInt(1, headImgId);
			pstmt.setInt(2, userId);
			int urs = pstmt.executeUpdate();
			if(urs != 0) {
				result = 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}
}
